from django.core.cache import cache
from system.models import Setting


class SettingService:
    def get_cache_key(self, key):
        return f'SYSTEM_SETTING:{key}'

    def set(self, key, value):
        Setting.objects.update_or_create(
            key=key,
            defaults={
                'value': value
            }
        )
        cache.set(self.get_cache_key(key), value, 60*30)

    def get(self, key):
        value = cache.get(self.get_cache_key(key), None)
        if not value:
            instance = Setting.objects.filter(key=key).first()
            value = instance.value if instance else None
            cache.set(self.get_cache_key(key), value, 60*30)
        return value


setting_service = SettingService()
